<template>
  <div class="goodsConfig h100" v-loading="loading">
    <div class="pageContent">
      <el-form :model="ruleForm" :inline="true" ref="ruleForm" label-width="80px">
        <el-row :gutter="11" class="fileSearch">
          <el-form-item label="类型:" prop="specificType">
            <!-- <el-input v-model="ruleForm.fullName" clearable></el-input> -->
            <el-select v-model="ruleForm.specificType" placeholder="请选择类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="纪念馆背景图片" value="backgroundImg"></el-option>
              <el-option label="纪念馆祭祀图片" value="sacrificeImg"></el-option>
              <el-option label="纪念馆背景音乐" value="backgroundMp3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="onSubmit(1)">
              查询
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            <el-button icon="el-icon-plus" type="success" @click="dialogVisible = true"
              >新增</el-button
            >
          </el-form-item>
        </el-row>
        <div class="table_wrapper">
          <el-table
            :data="tableData"
            border
            :header-cell-style="{
              background: 'rgb(246,247,251)',
              color: '#606266',
            }"
            stripe
            class="defaultTableHeight"
          >
            <el-table-column type="index" label="编号" width="50"> </el-table-column>
            <el-table-column prop="title" align="center" label="名称"> </el-table-column>
            <el-table-column align="center" label="类型">
              <template slot-scope="scope">
                {{ scope.row.specificType | specificTypeName }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="price" align="center" label="收费价格(祭祀币)">
          </el-table-column>
          <el-table-column
            prop="originalPrice"
            align="center"
            label="免费价格(祭祀币)"
          >
          </el-table-column> -->
            <!-- <el-table-column prop="vipPrice" align="center" label="VIP价格">
          </el-table-column> -->
            <!-- <el-table-column prop="sales" align="center" label="销量">
          </el-table-column> -->
            <!-- <el-table-column prop="validTime" align="center" label="有效天数">
          </el-table-column> -->
            <el-table-column prop="description" align="center" label="描述">
            </el-table-column>
            <el-table-column align="center" label="图片/音乐" width="300px">
              <template slot-scope="scope">
                <img
                  class="img_bgc bgc"
                  v-if="scope.row.specificType == 'backgroundImg'"
                  :src="scope.row.fileUrl"
                  alt=""
                />
                <img
                  class="img_bgc"
                  v-if="scope.row.specificType == 'sacrificeImg'"
                  :src="scope.row.fileUrl"
                  alt=""
                />
                <audio
                  v-if="scope.row.specificType == 'backgroundMp3'"
                  :src="scope.row.fileUrl"
                  controls
                ></audio>
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.state === 1" type="success">收费</el-tag>
              <el-tag v-if="scope.row.state === 0" type="info">免费</el-tag>
            </template>
          </el-table-column> -->
            <el-table-column label="操作" align="center" width="200px">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="updataGoods(scope.row.id)"
                  >编辑</el-button
                >
                <!-- <el-button
                type="danger"
                size="mini"
                @click="delGoods(scope.row.id)"
                >删除</el-button
              > -->
              </template>
            </el-table-column>
          </el-table>
          <p style="text-align: right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pager.currentPage"
              :page-size="pager.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="total,sizes,prev, pager, next, jumper"
              :total="pager.total"
            >
            </el-pagination>
          </p>
        </div>
      </el-form>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="600px"
      v-dialogDrag
      @close="closeDialog"
      @opened="opened"
    >
      <el-form
        ref="goodsForm"
        :model="goodsForm"
        :rules="goodsFormRules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="title">
          <el-input ref="input" v-model="goodsForm.title"></el-input>
        </el-form-item>
        <!-- <el-form-item label="免费价格" prop="originalPrice">
          <el-input
            v-model.number="goodsForm.originalPrice"
            readonly
          ></el-input>
        </el-form-item>
        <el-form-item label="收费价格" prop="price">
          <el-input v-model.number="goodsForm.price"></el-input>
        </el-form-item>
        <el-form-item label="有效时间" prop="validTime">
          <el-input
            v-model.number="goodsForm.validTime"
            placeholder="单位:天"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="类型">
          <el-select
            v-model="goodsForm.specificType"
            @change="goodsForm.fileUrl = ''"
            placeholder="请选择类型"
          >
            <el-option label="纪念馆背景图片" value="backgroundImg"></el-option>
            <el-option label="纪念馆祭祀图片" value="sacrificeImg"></el-option>
            <el-option label="纪念馆背景音乐" value="backgroundMp3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="goodsForm.specificType == 'backgroundImg'"
          style="height: 150px"
          label="上传背景图片"
          prop="unit"
        >
          <div
            v-if="goodsForm.fileUrl == ''"
            class="file_img img_text bgc"
            @click="imgClick"
          >
            上传图片
          </div>
          <img class="file_img bgc" :src="goodsForm.fileUrl" @click="imgClick" />
          <input
            class="file_input"
            type="file"
            accept=".png,.jpg,.jpeg"
            @change="change"
          />
        </el-form-item>
        <el-form-item
          v-if="goodsForm.specificType == 'sacrificeImg'"
          style="height: 120px"
          label="上传祭祀图片"
          prop="unit"
        >
          <div v-if="goodsForm.fileUrl == ''" class="file_img img_text" @click="imgClick">
            上传图片
          </div>
          <img class="file_img" :src="goodsForm.fileUrl" @click="imgClick" />
          <input
            class="file_input"
            type="file"
            accept=".png,.jpg,.jpeg"
            @change="change"
          />
        </el-form-item>
        <el-form-item
          v-if="goodsForm.specificType == 'backgroundMp3'"
          label="上传音乐"
          prop="unit"
        >
          <el-input v-model="musicName" readonly>
            <el-button slot="append" @click="imgClick">选择音乐</el-button></el-input
          >
          <audio v-if="goodsForm.fileUrl" :src="goodsForm.fileUrl" controls></audio>
          <input class="file_input" type="file" accept=".mp3" @change="change" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model.number="goodsForm.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveGoods" :loading="updateLoading"
            >保存</el-button
          >
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  memorialSpuImg_loadPageList,
  memorialSpuImg_operation,
  memorialSpuImg_delete,
  memorialSpuImg_loadOne,
} from "@/api/adminConfig/memorialBackground";
export default {
  name: "memorialBackground",
  data() {
    const isNumber = (rule, value, callback) => {
      if (!Number.isInteger(+value)) {
        callback(new Error("请输入数字值"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      dialogVisible: false,
      updateLoading: false,
      title: "纪念馆背景音乐/图片",
      musicName: "",
      ruleForm: {
        specificType: "",
        //   loginPhone: "",
        //   fullName: ""
      },
      pager: {
        pageSize: 20,
        total: 1,
        currentPage: 1,
      },
      tableData: [],
      goodsForm: {
        id: "",
        originalPrice: 0, //原价 /免费价格
        price: 0, //现价
        title: "",
        description: "",
        categoryId: "", //分类id
        specificType: "sacrificeImg",
        unit: "", //单位
        state: "1", //状态:(0:下架;1:正常销售)
        validTime: 0, //有效时间 天
        fileUrl: "",
      },
      goodsFormRules: {
        title: [{ required: true, message: "请输入名称", trigger: "blur" }],
        originalPrice: [
          { validator: isNumber, trigger: "blur" },
          { validator: isNumber, trigger: "change" },
        ],
        price: [
          { validator: isNumber, trigger: "blur" },
          { validator: isNumber, trigger: "change" },
        ],
        validTime: [
          { validator: isNumber, trigger: "blur" },
          { validator: isNumber, trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.onSubmit();
    // this.onloadGoodsList();
  },
  filters: {
    specificTypeName(val) {
      switch (val) {
        case "backgroundImg":
          return "纪念馆背景图片";
          break;
        case "sacrificeImg":
          return "纪念馆祭祀图片";
          break;
        case "backgroundMp3":
          return "纪念馆背景音乐";
          break;
        default:
          return;
      }
    },
  },
  //注销window.onresize事件
  destroyed() {},
  methods: {
    async onSubmit(val) {
      if (val) {
        this.pager.currentPage = 1;
      }
      this.loading = true;
      let postData = {
        pageSize: this.pager.pageSize,
        currentPage: this.pager.currentPage,
        specificType: this.ruleForm.specificType,
      };
      try {
        const res = await memorialSpuImg_loadPageList(postData);
        console.log(res, 200);
        this.loading = false;
        if (res.code != 2000) {
          this.$message(res.msg ? res.msg : "数据读取失败");
          return;
        }
        this.tableData = res.data;
        this.pager.pageSize = res.pageSize;
        this.pager.total = res.total;
        this.pager.currentPage = res.currentPage;
        //数据读取成功
      } catch (err) {
        console.log(err, 404);
        this.$message.error(err.msg);
        this.loading = false;
        this.tableData = [];
      }
    },
    // 触发图片选择
    imgClick() {
      document.querySelector("input[type=file]").click();
    },
    // 选择图片
    change() {
      let file = document.querySelector("input[type=file]").files[0];
      var reader = new FileReader();
      var that = this;
      console.log("base64", file);
      if (this.goodsForm.specificType == "backgroundMp3") {
        if (file.type == "audio/mpeg" || file.type == "audio/mp3") {
          this.musicName = file.name;
        } else {
          this.$message("只能上传文件格式为mp3的音频文件");
          return;
        }
      }
      reader.onloadend = function () {
        //把转换后的数据给id为base64Img的src属性
        console.log(reader.result);
        that.goodsForm.fileUrl = reader.result;

        //这里调用了向后台发请求的代码
      };
      if (file) {
        reader.readAsDataURL(file);
      }
    },

    // 修改按钮点击事件
    async updataGoods(id) {
      this.loading = true;
      let postData = {
        id,
      };
      console.log(postData, "postData");
      try {
        const res = await memorialSpuImg_loadOne(postData);
        console.log(res, 200);
        this.loading = false;
        if (res.code !== "2000") {
          this.message.error(res.msg ? res.msg : "信息获取失败");
          return;
        }
        this.dialogVisible = true;
        this.title = "修改商品";
        this.goodsForm = res.data;
      } catch (err) {
        this.loading = false;
        this.$message.error(err.msg);
        console.log(err, 404);
      }
    },
    // 新增保存-/-保存修改
    async saveGoods() {
      this.$refs["goodsForm"].validate(async (valid) => {
        if (valid) {
          this.updateLoading = true;
          this.loading = true;
          let postData = JSON.parse(
            JSON.stringify(this.goodsForm).replace(/fileUrl/g, "fileBase64")
          );
          console.log(postData, "postData");
          try {
            const res = await memorialSpuImg_operation(postData);
            console.log(res, 200);
            this.updateLoading = false;
            this.loading = false;
            if (res.code !== "2000") {
              this.$message.error(res.msg ? res.msg : "操作失败");
              return;
            }
            this.onSubmit();
            this.$message.success("操作成功");
            this.dialogVisible = false;
          } catch (err) {
            this.updateLoading = false;
            this.loading = false;
            this.$message.error(err.msg);
            console.log(err, 404);
          }
        }
      });
    },
    opened() {
      this.$refs.input.focus();
    },
    // 关闭弹窗的回调
    closeDialog() {
      this.goodsForm = {
        id: "",
        originalPrice: 0, //原价 /免费价格
        price: 0, //现价
        title: "",
        description: "",
        categoryId: "", //分类id
        specificType: "sacrificeImg",
        unit: "", //单位
        state: "1", //状态:(0:下架;1:正常销售)
        validTime: 0, //有效时间 天
        fileUrl: "",
      };
      document.querySelector("input[type=file]").value = "";
      this.$refs["goodsForm"].resetFields();
      this.dialogVisible = false;
      this.musicName = "";
    },
    //  删除
    async delGoods(id) {
      let postData = {
        ids: [id],
      };
      console.log(postData, "postData");
      try {
        const res = await memorialSpuImg_delete(postData);
        console.log(res, 200);

        if (res.code != 2000) {
          this.$message.error(res.msg ? res.msg : "操作失败");
          return;
        }
        this.$message.success("操作成功");
        this.onSubmit();
      } catch (err) {
        console.log(err, 404);
        this.$message.error(err.msg);
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["ruleForm"].resetFields();
      this.onSubmit();
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pager.pageSize = size;
      this.onSubmit();
    },
    handleCurrentChange: function (currentPage) {
      this.pager.currentPage = currentPage;
      this.onSubmit(); //点击第几页
    },
  },
};
</script>

<style lang="scss" scoped>
.fileSearch {
  .el-button {
    margin-left: 20px;
  }
}
.img_text {
  text-align: center;
  background-color: #fff;
  line-height: 100px;
  z-index: 1;
  border: 1px solid #f0f0f0;
}
.file_img {
  position: absolute;
  top: 9px;
  width: 100px;
  height: 100px;
  cursor: pointer;
}
.file_input {
  color: #ffffff00;
  display: none;
  width: 100px;
  height: 100px;
}
.img_bgc {
  width: 100px;
  height: 100px;
}
.bgc {
  height: 150px;
}
audio {
  width: 250px;
}
.el-dialog {
  audio {
    width: 300px;
    margin-top: 10px;
  }
}
</style>
